package com.example.backend2.controller;

import com.example.backend2.context.LoginMemberContext;
import com.example.backend2.domain.Role;
import com.example.backend2.domain.User;
import com.example.backend2.exception.BusinessException;
import com.example.backend2.exception.BusinessExceptionEnum;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
public class UserController {

    @Role(value = Role.GUEST)
    @PostMapping("/api/login")
    public ResponseEntity<Void> login(@RequestParam String username, @RequestParam String password, HttpServletRequest req) {
        // 登录 模拟数据
        User user = new User();
        user.setUsername("lzq");
        user.setPassword("lzq");

        User loginMember = (User)req.getSession().getAttribute("loginMember");
        if (loginMember != null && username.equals(loginMember.getUsername())) {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ALREADY_LOGIN);
        }
        if (username == null || password == null) {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USERNAME_PASSWORD_EMPTY);
        }

        if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
            // 登录成功
            HttpSession session = req.getSession();
            session.setAttribute("loginMember", user);
            LoginMemberContext.setMember(user);
            return ResponseEntity.ok().build();
        } else {
            // 登录失败
            throw new BusinessException(BusinessExceptionEnum.MEMBER_LOGIN_ERROR);
        }
    }

    @Role(value = Role.USER)
    @GetMapping("/api/user")
    public ResponseEntity<Void> getUser(@RequestParam String id) {
        return ResponseEntity.ok().build();
    }

    @Role(value = Role.ADMIN)
    @DeleteMapping("/api/user")
    public ResponseEntity<Void> deleteUser(@RequestParam String id) {
        return ResponseEntity.ok().build();
    }
}